/*
 *  Copyright 2007-2008 by Matthias Buch-Kromann <mbk.isv@cbs.dk>.
 *  *
 *  This file is part of the Open-source Dependency Toolkit (OSDT),
 *  see http://code.google.com/p/open-source-dependency-toolkit.
 *  
 *  The OSDT is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as 
 *  published by the Free Software Foundation, either version 3 of 
 *  the License, or (at your option) any later version.
 * 
 *  The OSDT is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 * 
 *  You should have received a copy of the GNU Lesser General Public 
 *  License along with the OSDT in the files COPYING and COPYING.LESSER.
 *  If not, see http://www.gnu.org/licenses.
 */

package org.osdtsystem.functions;

import java.util.List;
import org.osdtsystem.graphs.GraphAccessor;

/**
 *
 * @param <V> 
 * @param <W> 
 * @author Matthias Buch-Kromann <mbk.isv@cbs.dk>
 */
class FuncArgMinMax<V,W extends Object & Comparable<? super W>> extends AbstractSingletonFunction<V> {
    Function<? extends V> generator;
    SingletonFunction<W> value;
    String var;
    boolean maximize;
    
    public FuncArgMinMax(FuncVariable<V> var, Function<? extends V> generator, 
            SingletonFunction<W> value, boolean maximize) {
        super(generator, value);
        this.generator = generator;
        this.value = value;
        this.var = var.unaryVariable();
        this.maximize = maximize;
        addLocalBoundVariable(this.var);
    }

    @Override
    public V _singletonFunctionValue(LocalFunction<?, ?> caller, FunctionContext context,
            GraphAccessor accessor) {
        List<? extends V> generated = generator.functionValue(caller, context, accessor);
        V argmax = null;
        W valmax = null;
        for (V arg : generated) {
            // Save state and set variable
            int state = context.state();
            context.pushVariable(var, arg);
            
            // Add node if it satisfies condition
            W val = value.singletonFunctionValue(caller, context, accessor);
            if (valmax == null || (maximize ^ valmax.compareTo(val) > 0)) {
                valmax = val;
                argmax = arg;
            }
            
            // Restore state
            context.restoreState(state);
        }
        
        return argmax;
    }

    @Override
    public void toStringBuilder(FunctionStringBuilder b) {
        b.addParameter("var", var);
        b.addSubfunction("gen", generator);
        b.addSubfunction("val", value);
    }
}
